/*
 * BluePadDiscoverer.java
 *
 * Created on February 24, 2007, 3:34 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.bloomingstars.bluepad.desktop.client;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;

/**
 *
 * @author toni
 */
public final class BluePadDiscoverer
{    
    OutputStream out;
    DataInputStream in;
    
    public void writeString(String s) throws IOException
    {       
       if (out != null)
       {
           System.out.println("Now writing: " + s);
           out.write(s.getBytes());
           out.flush();
       }
    }
    
    public void pause(long millis)
    {
        System.out.println("Starting " + ((float) millis / 1000.0) + "-second pause");
        try
        {
          Thread.sleep(millis);
        }
        catch (InterruptedException ie)
        {
            
        }
        
        System.out.println("Pause ended");
    }
    
    public void execute()
    {
        try
        {
            LocalDevice localDevice = LocalDevice.getLocalDevice();
            DiscoveryAgent discoveryAgent = localDevice.getDiscoveryAgent();
            
            BluePadDiscoveryListener listener = new BluePadDiscoveryListener(this);
            
            System.out.println("Starting device inquiry...");
            discoveryAgent.startInquiry(DiscoveryAgent.GIAC, listener);
            
            // Wait for device discovery to end
            synchronized (this)
            {
                try
                {
                    wait();
                }
                catch (InterruptedException iex)
                {
                    iex.printStackTrace(System.err);
                }
            }
            System.out.println("Device inquiry ended...");
            
            List<RemoteDevice> remoteDevices = listener.getRemoteDevicesDiscovered();
            
            Iterator<RemoteDevice> it = remoteDevices.iterator();

            if (it.hasNext())
            {
                RemoteDevice remoteDevice = it.next();
                                
                
                System.out.println("Starting service search...");
                UUID[] uuids = new UUID[1];
                //uuids[0] = new UUID(0x1101); // SPP
                //uuids[0] = new UUID(0x0008); // SPP
                uuids[0] = new UUID(0x0003); // RFCOMM
                //uuids[2] = new UUID(0x0100); // L2CAP
                //int transId = agent.searchServices(null, nullnew UUID[] { }, remoteDevice, this );
                int[] attrSet = { 0, 1, 2, 3, 4, 256 };
                int transId = discoveryAgent.searchServices(attrSet, uuids, remoteDevice, listener);
                
                // Wait for service discovery to end
                synchronized (this)
                {
                    try
                    {
                        wait();
                    }
                    catch (InterruptedException iex)
                    {
                        iex.printStackTrace(System.err);
                    }
                }
                System.out.println("Service discovery ended...");
                
                // Service discovery ended. Try to open connection
                List<ServiceRecord> services = listener.getServicesDiscovered();
                Iterator<ServiceRecord> it1 = services.iterator();
                
                if (it1.hasNext())
                {
                    ServiceRecord sr = it1.next();
                    String url  = sr.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false );
                    
                    System.out.println("URL: " + url);
                    
                    try
                    {
                        
                      // code needed for keyboard input
                      /*BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                      System.out.println("B4 readline");
                      br.readLine();
                      br.close();
                      System.out.println("After readline");*/
                      
                      
                      // obtain connection and stream to this service
                      StreamConnection con = (StreamConnection) Connector.open( url );
                      System.out.println("connected to server");

                      Thread.sleep(1000);
                      
                      out = con.openOutputStream();
                      

                      // Version
/*                      writeString(":GVN#");
                      Thread.sleep(2000);
                      readString();
                      writeString(":GVP#");
                      Thread.sleep(2000);
                      readString();*/

                      // Get declination
                      writeString(":GR#");
                      Thread.sleep(2000);

                      in = con.openDataInputStream();
                      DA2Reader reader = new DA2Reader(in);
                      new Thread(reader).start();
                      
                      // Get declination
                      writeString(":GR#");
                      Thread.sleep(2000);

                      // Get declination
                      writeString(":GD#");
                      Thread.sleep(2000);
                      
                      // Change speed
                      /*writeString(":RG#");
                      Thread.sleep(2000);
                      
                      writeString(":RC#");
                      Thread.sleep(2000);

                      writeString(":RM#");
                      Thread.sleep(2000);

                      writeString(":RS#");
                      Thread.sleep(2000);

                      writeString(":RM#");
                      Thread.sleep(2000);
                      
                      System.out.println("Starting slew cycle...");
                      Thread.sleep(2000);
                      
                      // Nord
                      writeString(":Mn#");
                      Thread.sleep(3000);
                      writeString(":Qn#");

                      pause(3000);

                      // Est
                      writeString(":Me#");
                      Thread.sleep(3000);
                      writeString(":Qe#");

                      pause(3000);
                      
                      // Est
                      writeString(":Ms#");
                      Thread.sleep(3000);
                      writeString(":Qs#");

                      pause(3000);

                      // Ovest
                      writeString(":Mw#");
                      Thread.sleep(3000);
                      writeString(":Qw#");*/

                      pause(3000);
                      
                      /* write data into serial stream
                      out.write(msg2.getBytes());
                      out.flush();
                      System.out.println("write and flush 2 ok");
                      Thread.sleep(1000);
                           
                      System.out.println("Now writing '#Me#'");
                      out.write(":Me#".getBytes());
                      out.flush();
                      System.out.println("Written '#Me#'");
                      Thread.sleep(3000);
                      System.out.println("Now writing '#Me#'");
                      out.write(":Qe#".getBytes());
                      out.flush();
                      System.out.println("Written '#Qe#'");
                      Thread.sleep(1000);

                      System.out.println("Now writing '#Mn#'");
                      out.write(":Mn#".getBytes());
                      out.flush();
                      System.out.println("Written '#Mn#'");
                      Thread.sleep(3000);
                      System.out.println("Now writing '#Mn#'");
                      out.write(":Qn#".getBytes());
                      out.flush();
                      System.out.println("Written '#Qn#'");
                      Thread.sleep(1000);*/
                      
                      // finish, close output stream
                      out.close();
                      
                      // now the server should have echo back the string, so we read it
                      // using input stream
                      //DataInputStream in = con.openDataInputStream();
                      // String s = in.readUTF();
                      in.close();
                      con.close();

                    } catch (Exception e)
                    {
                      e.printStackTrace();                      
                    }
                    
                }
            }                       
        }
        catch (BluetoothStateException e)
        {
            System.err.println("Problems while inquiring for devices");
            e.printStackTrace();
        }
    }
    
}

class DA2Reader implements Runnable
{
    InputStream in;
    
    public DA2Reader(InputStream in)
    {
        this.in = in;
    }
    
    public void run()
    {
        try
        {
            System.out.println("Receiver thread started");
            Thread.sleep(250);
            while (true)
            {                
                // byte[] buffer = new byte[256];
                
                if (in != null) // && in.available()>0)
                {           
                    int b = in.read();
                    System.out.println("Read: " + (char) b);
                }
                else
                {
                    System.out.println("Nothing to read");
                }
                
            }
        }
        catch (Exception ex)
        {
            System.err.println("Error in receiver thread");
            ex.printStackTrace(System.err);
        }
    }        
}
